//
//  SAShopSaleVC.m
//  saasRetail
//
//  Created by 黄志刚 on 2021/4/9.
//

#import "SAShopSaleVC.h"
#import "SASelectShopVC.h"
#import "ScanHelper.h"
#import "SAShopSaleCell.h"
#import "SASalesOrderViewListModel.h"
#import "HDDatePickerView.h"
#import "SASearchStoreUserView.h"
#import "SASearchVipUserView.h"
#import "SAInputDiscountView.h"
#import "SASystemSettingsListAPI.h"
#import "UILabel+NSMutableAttributedString.h"
#import "SACollectionPayView.h"
#import "SAPayCombinationVC.h"
#import "SASalesSaveAPI.h"
#import "SASaleDocumentsVC.h"
#import "SASalesInvoiceDetailAPI.h"
#import "SASalesInvoiceDetailModel.h"
#import "SASystemEmpDetailAPI.h"
#import "SASalesProductListAPI.h"
#import "SACommodityAddShopSizeView.h"
#import "YBImageBrowser.h"
#import "SACloudPrintPushPrintMsgAPI.h"
#import "SASalesOrderStatementErrorModel.h"
#import "SASalesOrderStatementErrorView.h"
#import "SAShopSaleFooterView.h"
#import "SAMarketingListModel.h"
#import "SASalesSalesPayAPI.h"
#import "SAReceiveQueryStatusAPI.h"
#import "GFAlertView.h"
#import "SAGetPayPermissionAPI.h"
#import "NSString+nonce.h"
#import "NSString+MD5.h"
#import "SAQueryPrinterStatusAPI.h"
#import "SAPrintTicketAPI.h"
#import "SAAllInProgressActivityAPI.h"
#import "SAGetOrgMerchantSettingsAPI.h"

@interface SAShopSaleVC ()<UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate, UITextFieldDelegate, YBImageBrowserDataSource>

@property (nonatomic, strong) UIButton *empBtn;
@property (nonatomic, strong) UIButton *dateBtn;
@property (nonatomic, strong) UIButton *vipBtn;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) float tableViewTop;
@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *dataMarr;
@property (nonatomic, strong) UIView *footView;
@property (nonatomic, strong) UIView *integralView;

@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) UIButton *addBtn;
@property (nonatomic, assign) BOOL isVip;
@property (nonatomic, strong) SASearchStoreUserView *searchStoreUserView;
@property (nonatomic, strong) SASearchVipUserView *searchVipUserView;
@property (nonatomic, strong) SAVipModel *vipModel;
@property (nonatomic, strong) SAStoreUserModel *userModel;

@property (nonatomic, strong) SASystemSettingsListAPI *systemSettingsListAPI;
@property (nonatomic, strong) UITextField *discountTf;
@property (nonatomic, strong) NSString *discount;
@property (nonatomic, assign) double vipDiscount;
@property (nonatomic, strong) NSString *limit;
@property (nonatomic, assign) BOOL pointSwitch;
@property (nonatomic, strong) UILabel *shopLab;
@property (nonatomic, strong) UILabel *shopPirceLab;
@property (nonatomic, strong) UILabel *shopPirce1Lab;
@property (nonatomic, strong) UILabel *shopPirce2Lab;
@property (nonatomic, strong) UILabel *integralLab;
@property (nonatomic, strong) UITextField *allDiscountTf;
@property (nonatomic, strong) UITextField *discountPriceTf;
@property (nonatomic, strong) UILabel *totalCountLab;
@property (nonatomic, strong) SASalesSaveAPI *salesSaveAPI;

@property (nonatomic, strong) NSString *type;
@property (nonatomic, assign) double totalPrice;
@property (nonatomic, strong) SASalesInvoiceDetailAPI *salesInvoiceDetailAPI;
@property (nonatomic, strong) SASystemEmpDetailAPI *systemEmpDetailAPI;
@property (nonatomic, strong) NSString *isSuperposition;//会员折扣是否叠加
@property (nonatomic, assign) CGFloat sendIntegral;
@property (nonatomic, strong) NSString *mvoeZero;
@property (nonatomic, strong) NSString *payType;
@property (nonatomic, strong) SASalesProductListAPI *salesProductListAPI;
@property (nonatomic, strong) NSArray *imageList;

@property (nonatomic, assign) BOOL isEditText;
@property (nonatomic, assign) BOOL isNegative;//是否限制负库存销售 yes限制 no不限制
@property (nonatomic, strong) SAOverallSetting *overallSetting;
@property (nonatomic, strong) SACloudPrintPushPrintMsgAPI *cloudPrintPushPrintMsgAPI;

@property (nonatomic, assign) BOOL isScanPay;
@property (nonatomic, assign) BOOL isScan;
@property (nonatomic, strong) NSString *salesOrderId;
@property (nonatomic, strong) NSString *salesOrderNo;
@property (nonatomic, strong) SASalesSalesPayAPI *salesSalesPayAPI;
@property (nonatomic, strong) SAReceiveQueryStatusAPI *receiveQueryStatusAPI;

@property (nonatomic, assign) BOOL isPolling;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) int count;

@property (nonatomic, strong) SAGetPayPermissionAPI *getPayPermissionAPI;
@property (nonatomic, assign) BOOL isCanPay;
@property (nonatomic, strong) UITextField *cardStockTf;
@property (nonatomic, strong) NSString *randomStr;
@property (nonatomic, strong) UITextField *remarkTf;

@property (nonatomic, strong) SAQueryPrinterStatusAPI *queryPrinterStatusAPI;
@property (nonatomic, strong) SASalesInvoiceDetailModel *printModel;
@property (nonatomic, strong) SAPrintTicketAPI *printTicketAPI;

@property (nonatomic, strong) NSMutableArray<SASalesOrderViewListModel *> *giveDataMarr;

@property (nonatomic, strong) NSString *zeroAmount;//抹零的金额

@property (nonatomic, strong) SAAllInProgressActivityAPI *allInProgressActivityAPI;
@property (nonatomic, strong) NSMutableArray<SAMarketingListModel *> *marketingMarr;
@property (nonatomic, strong) UIView *MarketingListModelView;

@property (nonatomic, strong) UILabel *marketingLab;//活动满减金额
@property (nonatomic, assign) BOOL isIndividualDiscount;//散客是否享受折扣
@property (nonatomic, strong) UILabel *vipIntegralLab;//会员积分

@property (nonatomic, strong) UIView *remarkView;
@property (nonatomic, strong) UIView *whiteView;
@property (nonatomic, strong) UIView *whiteView2;

@property (nonatomic, strong) NSString *defaultPayType;//支付类型
@property (nonatomic, strong) SAGetOrgMerchantSettingsAPI *getOrgMerchantSettingsAPI;

@end

@implementation SAShopSaleVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemSettingsListAPI == api) {
        
        self.defaultPayType = data[@"data"][@"priority_payment_method"][@"value"];
        
        NSString *negative = data[@"data"][@"negative_stock_out"][@"value"];
        if ([negative isEqualToString:@"1"]) {
            self.isNegative = NO;
        }else {
            self.isNegative = YES;
        }
        NSArray *mvoeArr = data[@"data"][@"special_cost"][@"childSettings"];;
        for (NSDictionary *dic in mvoeArr) {
            NSString *code = dic[@"code"];
            if ([code isEqualToString:@"wipe_zero"]) {
                self.mvoeZero = dic[@"value"];
            }
        }
        NSString *rounding = data[@"data"][@"rounding"][@"value"];
        if ([rounding isEqualToString:@"1"]) {
            if ([self.mvoeZero isEqualToString:@"1"]) {
                self.mvoeZero = @"3";
            }else if ([self.mvoeZero isEqualToString:@"2"]) {
                self.mvoeZero = @"4";
            }
        }
        
        NSString *individualDiscount = data[@"data"][@"individual_discount"][@"value"];
        if ([individualDiscount isEqualToString:@"1"]) {
            self.isIndividualDiscount = NO;
        }else {
            self.isIndividualDiscount = YES;
        }
        
        NSArray *arr = data[@"data"][@"member_points_setting"][@"childSettings"];
        NSString *sendIntegral = @"0";
        for (NSDictionary *dic in arr) {
            NSString *code = dic[@"code"];
            if ([code isEqualToString:@"consumption_gift"]) {
                sendIntegral = dic[@"value"];
            }
        }
        NSDictionary *discountDic = data[@"data"][@"discount_setting"];
        self.isSuperposition = [NSString stringWithFormat:@"%@",discountDic[@"value"]];
        
        NSArray *sendArr = [sendIntegral componentsSeparatedByString:@","];
        if (sendArr.count > 1) {
            NSString *str1 = sendArr[0];
            NSString *str2 = sendArr[1];
            if ([str2 integerValue] > 0) {
                self.sendIntegral = [str1 integerValue] / [str2 integerValue];
            }else {
                self.sendIntegral = 0;
            }
        }
        if ([self.limit integerValue] > 0 && [self.discount integerValue] > 0) {
            self.discountTf.userInteractionEnabled = YES;
            self.discountTf.placeholder = [NSString stringWithFormat:@"%0.f积分可抵扣%@",[self.discount doubleValue] *  [self.limit doubleValue],self.limit];
        }else {
            self.discountTf.placeholder = @"请先设置抵扣比例";
            self.discountTf.userInteractionEnabled = NO;
        }
        
        //权限处理
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *salesDiscount = [NSString stringWithFormat:@"%@",menuList[11][@"perms"][@"salesDiscount"]];
        if ([salesDiscount isEqualToString:@"1"]) {
            self.discountTf.userInteractionEnabled = NO;
        }
        
    }else if (self.salesSaveAPI == api) {
        NSInteger status = [data[@"status"] integerValue];
        self.salesOrderId = data[@"data"][@"salesOrderId"];
        self.salesOrderNo = data[@"data"][@"salesOrderNo"];
        if (self.isScanPay == YES) {
            if (status == 2) {
                self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
                [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
                [self clearData];
                [Prompt popPromptViewWithMsg:@"结账成功" duration:2];
            }else if (status == 0) {
                [self scanQrcode];
            }
        }else {
            self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
            [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
            [self clearData];
            [Prompt popPromptViewWithMsg:@"结账成功" duration:2];
        }
    }else if (self.salesInvoiceDetailAPI == api) {
        SASalesInvoiceDetailModel *salesInvoiceDetailModel = [SASalesInvoiceDetailModel mj_objectWithKeyValues:data[@"data"]];
        self.printModel = salesInvoiceDetailModel;
        if (self.overallSetting.printerSetting.printerStatus == 2 && [SAValueManger shareInStance].printType == 1) {
            [SAPrintReceiptSell printWithTotalData:salesInvoiceDetailModel printSuccessBlock:^{
                
            }];
        }else {
            [self.queryPrinterStatusAPI submitForm:POST];
        }
    }else if (self.systemEmpDetailAPI == api) {
        self.userModel = [SAStoreUserModel mj_objectWithKeyValues:data[@"data"]];
    }else if (self.salesProductListAPI == api) {
        WeakSelf
        NSMutableArray *marr = [SASalesOrderViewListModel mj_objectArrayWithKeyValuesArray:data[@"data"][@"records"]];
        if (marr.count == 1) {
            SASalesOrderViewListModel *model = marr[0];
            model.percentage = [model.discountRate floatValue] / 10000;
            model.priceType = @"-1";
            model.salePrice = [model.retailPrice floatValue] * model.percentage;
            model.isNegative = self.isNegative;
            model.toPendSkuAttrs = [NSMutableArray array];
            for (SASalesOrderToPendSkuList *list in model.skuList) {
                SASalesOrderToPendSkuList *newList = [SASalesOrderToPendSkuList new];
                newList.colourId = list.colourId;
                newList.colourName = list.colourName;
                newList.sizeId = list.sizeId;
                newList.sizeName = list.sizeName;
                newList.stock = @"0";
                newList.skuId = list.skuId;
                newList.inventoryCount = list.stock;
                newList.price = model.retailPrice;
                [model.toPendSkuAttrs addObject:newList];
            }
            //判断model是否已经存在
            __block SASalesOrderViewListModel *dataModel = nil;
            for (SASalesOrderViewListModel *oldModel in weakSelf.dataMarr) {
                if ([oldModel.productId isEqualToString:model.productId]) {
                    dataModel = oldModel;
                }
            }
            
            if (dataModel != nil) {
                dataModel.targetSkuList = model.targetSkuList;
                model = dataModel;
            }
            
            //如果只有一个颜色尺码直接加1
            if (model.targetSkuList.count == 1) {
                NSString *skuId = model.targetSkuList[0].skuId;
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.skuId isEqualToString:skuId]) {
                        NSInteger stock = [list.stock integerValue] + 1;
                        list.stock = [NSString stringWithFormat:@"%zd",stock];
                    }
                }
                BOOL isZero = YES; //判断数据是否全是0，是就不添加
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock integerValue] != 0) {
                        isZero = NO;
                    }
                }
                if (isZero == NO) {
                    if (dataModel == nil) {
                        [weakSelf.dataMarr addObject:model];
                    }else {
                        dataModel = model;
                    }
                }else {
                    [weakSelf.dataMarr removeObject:model];
                }
                
                [weakSelf upData];
                [weakSelf setBottomUI];
                [weakSelf.tableView reloadData];
                return;
            }
            
            SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:model];
            addShopSizeView.isNegative = self.isNegative;
            addShopSizeView.isAll = YES;
            [addShopSizeView showView:self];
            addShopSizeView.showImageBlock = ^{
                [weakSelf showImage:model.imgList];
            };
            addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
                BOOL isZero = YES; //判断数据是否全是0，是就不添加
                for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                    if ([list.stock integerValue] != 0) {
                        isZero = NO;
                    }
                }
                if (isZero == NO) {
                    if (dataModel == nil) {
                        [weakSelf.dataMarr addObject:model];
                    }else {
                        dataModel = model;
                    }
                }else {
                    [weakSelf.dataMarr removeObject:model];
                }
                
                [weakSelf upData];
                [weakSelf setBottomUI];
                [weakSelf.tableView reloadData];
            };
        }else {
            [Prompt popPromptViewWithMsg:@"未查询到商品" duration:2];
        }
    }else if (self.cloudPrintPushPrintMsgAPI == api) {
        [Prompt popPromptViewWithMsg:@"正在进行共享打印" duration:2];
    }else if (self.salesSalesPayAPI == api) {
        NSInteger status = [data[@"status"] integerValue];
        if (status == 2) {
            self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
            [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
            [self clearData];
            [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
        }else if (status == 0) {
            self.isPolling = YES;
            self.count = 31;
            [HDHubView loadingMessage:@"正在查询支付状态..."];
            self.receiveQueryStatusAPI.orderNo = self.salesOrderNo;
            self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerFired) userInfo:nil repeats:YES];
        }else {
            [self tipAlertView:@"支付失败"];
        }
    }else if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            NSInteger status = [data[@"data"][@"status"] integerValue];
            if (status == 2) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                self.salesInvoiceDetailAPI.salesOrderId = self.salesOrderId;
                [self.salesInvoiceDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
                [self clearData];
                [Prompt popPromptViewWithMsg:@"支付成功" duration:2];
            }else if (status == 6 || status == 8) {
                self.isPolling = NO;
                [self.timer invalidate];
                self.timer = nil;
                [HDHubView dismissLoading];
                [self tipAlertView:@"支付失败"];
            }
        }
    }else if (self.getPayPermissionAPI == api) {
        NSString *isCanPayStr = [NSString stringWithFormat:@"%@",data[@"data"]];
        if ([isCanPayStr isEqualToString:@"0"]) {
            self.isCanPay = NO;
        }else {
            self.isCanPay = YES;
        }
    }else if (self.queryPrinterStatusAPI == api) {
        NSString *status = data[@"data"][@"status"];
        NSString *type = data[@"data"][@"type"];
        if ([status isEqualToString:@"1"] && [type isEqualToString:@"1"]) {
            self.printTicketAPI.ticketType = @"1";
            self.printTicketAPI.salesOrderId = self.printModel.saleOrderId;
            [self.printTicketAPI submitForm:POST];
        }else {
            if (kIsTestServer == 1) {
                self.cloudPrintPushPrintMsgAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
                self.cloudPrintPushPrintMsgAPI.type = @"1";
                self.cloudPrintPushPrintMsgAPI.data = self.printModel.saleOrderId;
                [self.cloudPrintPushPrintMsgAPI submitForm:POST];
            }else {
                [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
            }
        }
    }else if (self.allInProgressActivityAPI == api) {
        NSMutableArray<SAMarketingListModel *> *marketingList = [SAMarketingListModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        self.marketingMarr = [NSMutableArray array];
        for (SAMarketingListModel *model in marketingList) {
            //进行中的活动
            if ([model.status isEqualToString:@"1"]) {
                [self.marketingMarr addObject:model];
            }
        }
    }else if (self.self.getOrgMerchantSettingsAPI == api) {
        NSString *code = data[@"data"][@"code"];
        if ([code isEqualToString:@"points_switch"]) {
            self.pointSwitch = NO;
            NSString *value = data[@"data"][@"value"];
            NSArray *valueArr = [value componentsSeparatedByString:@","];
            if (valueArr.count > 2) {
                NSString *valueStr = valueArr[1];
                if ([valueStr integerValue] == 1) {
                    self.pointSwitch = YES;
                }
            }
            self.self.getOrgMerchantSettingsAPI.code = @"deduction";
            [self.getOrgMerchantSettingsAPI sendRequestToServerWithActivityViewAndMask:GET];
        } else if ([code isEqualToString:@"deduction"]) {
            self.discount = [NSString stringWithFormat:@"%@",data[@"data"][@"value"]];
            self.self.getOrgMerchantSettingsAPI.code = @"deduction_limit";
            [self.getOrgMerchantSettingsAPI sendRequestToServerWithActivityViewAndMask:GET];
        } else if ([code isEqualToString:@"deduction_limit"]) {
            self.limit = [NSString stringWithFormat:@"%@",data[@"data"][@"value"]];
            [self.systemSettingsListAPI sendRequestToServerWithActivityViewAndMask:GET];
        }
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    if (self.receiveQueryStatusAPI == api) {
        if (self.isPolling == YES) {
            self.isPolling = NO;
            [self.timer invalidate];
            self.timer = nil;
            [HDHubView dismissLoading];
            NSDictionary *dic = error.userInfo;
            NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
            [self tipAlertView:msg];
        }
    }else if (self.salesSalesPayAPI == api) {
        NSDictionary *dic = error.userInfo;
        NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
        [self tipAlertView:msg];
    }else if (self.salesSaveAPI == api) {
        NSDictionary *dict = error.userInfo;
        if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"20007"]) {
            NSDictionary *errorDic = [self dictionaryWithJsonString:dict[@"msg"]];
            NSMutableArray *errorArray = [NSMutableArray array];
            for (NSArray *errorLsit in errorDic) {
                SASalesOrderStatementErrorModel *model = [SASalesOrderStatementErrorModel mj_objectWithKeyValues:errorLsit];
                NSLog(@"%@",model);
                [errorArray addObject:model];
            }
            
            SASalesOrderStatementErrorView *screenView = [SASalesOrderStatementErrorView shareCornView];
            screenView.removeBlock = ^(NSArray * _Nonnull array) {
                for (SASalesOrderViewListModel *model in self.dataMarr) {
                    for (SASalesOrderToPendSkuList *skuList in [model.toPendSkuAttrs reverseObjectEnumerator]) {
                        for (SASalesOrderStatementErrorSkuList *errorList in array) {
                            if ([errorList.skuId isEqualToString:skuList.skuId]) {
                                [model.toPendSkuAttrs removeObject:skuList];
                                break;
                            }
                        }
                    }
                }
                
                NSMutableArray *newDataArray = [NSMutableArray array];
                for (SASalesOrderViewListModel *listModel in self.dataMarr) {
                    if (listModel.toPendSkuAttrs.count > 0) {
                        [newDataArray addObject:listModel];
                    }
                }
                self.dataMarr = newDataArray;
                if (self.dataMarr.count > 0) {
                    [self upData];
                    [self setBottomUI];
                    [self.tableView reloadData];
                }else {
                    [self clearData];
                }
            };
            [screenView loadData:errorArray];
            [screenView showView:nil];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50001"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clearData];
        }else if ([[NSString stringWithFormat:@"%@",dict[@"code"]] isEqualToString:@"50002"]) {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
            [self clearData];
        }else {
            NSString *msg = dict[@"msg"];
            [Prompt popPromptViewWithMsg:msg duration:3];
        }
    }else if (self.getPayPermissionAPI == api) {
        self.isCanPay = NO;
    }else if (self.queryPrinterStatusAPI == api) {
        if (kIsTestServer == 1) {
            self.cloudPrintPushPrintMsgAPI.merchantId = [SAValueManger shareInStance].userInfo.merchantId;
            self.cloudPrintPushPrintMsgAPI.type = @"1";
            self.cloudPrintPushPrintMsgAPI.data = self.printModel.saleOrderId;
            [self.cloudPrintPushPrintMsgAPI submitForm:POST];
        }else {
            [Prompt popPromptViewWithMsg:@"未连接打印机" duration:2];
        }
    }
}

#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataMarr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    SAShopSaleCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SAShopSaleCell" forIndexPath:indexPath];
    cell.isIndividualDiscount = self.isIndividualDiscount;
    SASalesOrderViewListModel *model = self.dataMarr[indexPath.section];
    cell.vipModel = self.vipModel;
    cell.model = model;
    if (indexPath.section == self.dataMarr.count - 1) {
        [self upData];//数据发生变化后，刷新统计的数据
    }
    cell.discountBlock = ^{
        NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
        NSString *salesDiscount = [NSString stringWithFormat:@"%@",menuList[11][@"perms"][@"salesDiscount"]];
        if ([salesDiscount isEqualToString:@"1"]) {
            return;
        }
        
        SAInputDiscountView *discountView = [SAInputDiscountView initViewTitle:@"" DiscountRate:model.percentage DiscountPrice:model.salePrice AndRetailPrice:[model.retailPrice floatValue]];
        UIWindow *window =  [UIApplication sharedApplication].keyWindow;
        [window addSubview:discountView];
        discountView.discountBlock = ^(CGFloat discountRate, CGFloat discountPrice, NSString * _Nonnull priceType) {
            model.percentage = discountRate;
            model.salePrice = discountPrice;
            model.priceType = priceType;
            
            //参加活动折上折处理
            model.activityPercentage = discountRate;
            model.activitySalePrice = discountPrice;
            if (self.isVip == YES) {
                if (model.isOpenActivity == YES && [model.memberDiscountStacking isEqualToString:@"1"]) {
                    model.percentage = discountRate * [weakSelf.vipModel.memberDiscount doubleValue]/100;
                    model.salePrice = discountPrice * [weakSelf.vipModel.memberDiscount doubleValue]/100;
                }
            }
            
            [weakSelf upData];
            [tableView reloadData];
        };
    };
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    WeakSelf
    if (self.isEditText == YES) {
        return;
    }
    __block SASalesOrderViewListModel *dataModel = self.dataMarr[indexPath.section];
    SACommodityAddShopSizeView *addShopSizeView = [[SACommodityAddShopSizeView alloc] initWithListModel:dataModel];
    [addShopSizeView showGive:self.dataMarr];
    addShopSizeView.isNegative = self.isNegative;
    addShopSizeView.isAll = YES;
    [addShopSizeView showView:self];
    addShopSizeView.showImageBlock = ^{
        [weakSelf showImage:dataModel.imgList];
    };
    addShopSizeView.selectBlock = ^(SASalesOrderViewListModel * _Nonnull model) {
        BOOL isZero = YES; //判断数据是否全是0，是就不添加
        for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
            if ([list.stock integerValue] != 0) {
                isZero = NO;
            }
        }
        if (isZero == NO) {
            dataModel = model;
        }else {
            [self.dataMarr removeObject:model];
        }
        [weakSelf upData];
        [weakSelf setBottomUI];
        [tableView reloadData];
    };
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(55);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    WeakSelf
    SASalesOrderViewListModel *dataModel = self.dataMarr[section];
    if (dataModel.isGive != YES && dataModel.activityId.length > 0) {
        SAShopSaleFooterView *footer = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SAShopSaleFooterView"];
        footer.dataModel = dataModel;
        footer.onBlock = ^(NSString * _Nonnull index) {
            for (SASalesOrderViewListModel *model in weakSelf.dataMarr) {
                if (![model.priceType isEqualToString:@"-1"] && [model.memberDiscountStacking isEqualToString:@"1"]) {
                    if ([index isEqualToString:@"1"]) {
                        model.percentage = model.activityPercentage * [weakSelf.vipModel.memberDiscount doubleValue]/100;
                        model.salePrice = model.activitySalePrice * [weakSelf.vipModel.memberDiscount doubleValue]/100;
                    }else {
                        model.percentage = model.activityPercentage;
                        model.salePrice = model.activitySalePrice;
                    }
                }
            }
            [weakSelf upData];
            [tableView reloadData];
        };
        return footer;
    }
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    SASalesOrderViewListModel *dataModel = self.dataMarr[section];
    if (dataModel.isGive != YES && dataModel.activityId.length > 0) {
        return kScaleNum(35);
    }
    return kScaleNum(0.01);
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

-(NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASalesOrderViewListModel *model = self.dataMarr[indexPath.section];
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDefault
                                                                         title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self.dataMarr removeObject:model];
        [self upData];
        [self.tableView reloadData];
        [self setBottomUI];
    }];
    rowAction.backgroundColor = kPinkColor;
    NSArray *arr = @[rowAction];
    return arr;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return @"删除";
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length == 0) {
        return YES;
    }
    if (textField.text.length > 8){
        return NO;
    }
    if (self.discountTf == textField && [string isEqualToString:@"."]) {
        return NO;//积分抵扣
    }
    if (self.allDiscountTf == textField) {
        if ([string isEqualToString:@"0"]) {
            if (textField.text.length == 0) {
                return NO;
            }
        }
        NSString *newStr = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if ([newStr doubleValue] > 10000) {
            return NO;
        }
    }
    if (self.discountPriceTf == textField) {
        NSString *price = [self.shopPirceLab.text stringByReplacingOccurrencesOfString:@"￥" withString:@""];
        NSString *newStr = [NSString stringWithFormat:@"%@%@",textField.text,string];
        if ([newStr doubleValue] > ([price doubleValue] * 100)) {
            return NO;
        }
    }
    
    if((textField.text.length == 0) && [string isEqualToString:@"."]) {
        textField.text = @"0";
    }
    if([textField.text containsString:@"."]) {
        if ([string isEqualToString:@"."]) {
            return NO;
        }
        NSRange ran = [textField.text rangeOfString:@"."];
        if(range.location > ran.location) {
            if([textField.text pathExtension].length > 1) {
                return NO;
            }
        }
    }
    return [self validateNumber:string];
}

- (void)textFieldEditChanged:(UITextField*)textField {
    if (self.discountTf == textField) {
        CGFloat input = [textField.text floatValue];
        CGFloat discountInput = [self.discount floatValue];
        if (self.vipDiscount < 0) {
            input = 0;
            if (textField.text.length > 0) {
                textField.text = @"0";
            }
        }else {
            if (input > self.vipDiscount) {
                input = self.vipDiscount;
                textField.text = [NSString stringWithFormat:@"%0.f",input];
            }
        }
        self.integralLab.text = [NSString stringWithFormat:@"可抵:%0.2f",floor(input/discountInput * 100)/100] ;
        [self countPrice];
    }else if (self.allDiscountTf == textField) {
        NSString *priceStr = [self.shopPirceLab.text stringByReplacingOccurrencesOfString:@"￥" withString:@""];
        double price = [[NSString stringWithFormat:@"%0.f",[priceStr doubleValue] * 100] doubleValue];
        NSInteger allDiscount = 10000;
        if (self.allDiscountTf.text.length > 0) {
            NSString *allDiscountStr = [NSString stringWithFormat:@"%0.f",[self.allDiscountTf.text floatValue] * 100];
            allDiscount = [allDiscountStr integerValue];
        }
        double discount = price * allDiscount / 100;
        self.discountPriceTf.text = [NSString stringWithFormat:@"%0.2lf",round(discount /100.f)/100];
        
        CGFloat discountPriceF = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] floatValue];
        double discountPrice = [[NSString stringWithFormat:@"%0.f",discountPriceF * 100] doubleValue];
        double totalPrice = [self.discountPriceTf.text doubleValue] * 100 - discountPrice - [self.cardStockTf.text doubleValue] * 100;;
        if (totalPrice < 0) {
            totalPrice = 0;
        }
        self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",totalPrice / 100];
        double newTotalPrice = [[NSString stringWithFormat:@"%0.f",totalPrice] doubleValue];
        if ([self.mvoeZero isEqualToString:@"1"]) {
            self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",floor(newTotalPrice/100)];
        }else if ([self.mvoeZero isEqualToString:@"2"]) {
            self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",floor(newTotalPrice / 10) / 10.f];
        }else if ([self.mvoeZero isEqualToString:@"3"]) {
            NSString *countStr = [NSString stringWithFormat:@"%0.lf",round(newTotalPrice/100.f)];
            self.totalCountLab.text = [NSString stringWithFormat:@"%@.00",countStr];
        }else if ([self.mvoeZero isEqualToString:@"4"]) {
            NSString *countStr = [NSString stringWithFormat:@"%0.1lf",round(newTotalPrice/10.f)/10];
            self.totalCountLab.text = [NSString stringWithFormat:@"%@0",countStr];
        }
        self.type = @"1";
        
        double totalCountD = [self.totalCountLab.text doubleValue] * 100;
        double zeroAmountD = newTotalPrice - totalCountD;
        self.zeroAmount = [NSString stringWithFormat:@"%0.lf",zeroAmountD];
        
    }else if (self.discountPriceTf == textField) {
        NSString *price = [self.shopPirceLab.text stringByReplacingOccurrencesOfString:@"￥" withString:@""];
        self.allDiscountTf.text = [NSString stringWithFormat:@"%0.2f", round([self.discountPriceTf.text doubleValue]/[price doubleValue] * 10000)/100];
        CGFloat discountPrice = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] floatValue];
        double totalPrice = [self.discountPriceTf.text doubleValue] - discountPrice - [self.cardStockTf.text doubleValue];
        if (totalPrice < 0) {
            totalPrice = 0;
        }
        self.type = @"0";
        self.totalCountLab.text = [NSString stringWithFormat:@"%0.2f",totalPrice];
        double newTotalPrice = [[NSString stringWithFormat:@"%0.f",totalPrice * 100] doubleValue];
        if ([self.mvoeZero isEqualToString:@"1"]) {
            self.totalCountLab.text = [NSString stringWithFormat:@"%0.2f",floor(newTotalPrice/100)];
        }else if ([self.mvoeZero isEqualToString:@"2"]) {
            self.totalCountLab.text = [NSString stringWithFormat:@"%0.2f",floor(newTotalPrice / 10) / 10.f];
        }else if ([self.mvoeZero isEqualToString:@"3"]) {
            NSString *countStr = [NSString stringWithFormat:@"%0.lf",round(newTotalPrice/100.f)];
            self.totalCountLab.text = [NSString stringWithFormat:@"%@.00",countStr];
        }else if ([self.mvoeZero isEqualToString:@"4"]) {
            NSString *countStr = [NSString stringWithFormat:@"%0.1lf",round(newTotalPrice/10.f)/10];
            self.totalCountLab.text = [NSString stringWithFormat:@"%@0",countStr];
        }
        
        double totalCountD = [self.totalCountLab.text doubleValue] * 100;
        double zeroAmountD = newTotalPrice - totalCountD;
        self.zeroAmount = [NSString stringWithFormat:@"%0.lf",zeroAmountD];
    }else if (self.cardStockTf == textField) {
        [self countPrice];
    }
}

- (BOOL)validateNumber:(NSString*)number {
    BOOL res = YES;
    NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@".0123456789"];
    int i = 0;
    while (i < number.length) {
        NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
        NSRange range = [string rangeOfCharacterFromSet:tmpSet];
        if (range.length == 0) {
            res = NO;
            break;
        }
        i++;
    }
    return res;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    self.isEditText = YES;
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.isEditText = NO;
    });
}

#pragma mark - event
-(void)clickedScanBtn {
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:notSquare qrResultCallBack:^(id result) {
        self.salesProductListAPI.currentPage = 1;
        self.salesProductListAPI.pageSize = 20;
        self.salesProductListAPI.productNameOrCode = result;
        [self.salesProductListAPI sendRequestToServerWithActivityViewAndMask:GET];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

-(void)clickedAddBtn {
    [self.giveDataMarr removeAllObjects];
    NSMutableArray<SASalesOrderViewListModel *> *newDataMarr = [NSMutableArray array];
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        if (model.isGive == YES) {
            [self.giveDataMarr addObject:model];
        }else {
            [newDataMarr addObject:model];
        }
    }
    SASelectShopVC *shopVC = [[SASelectShopVC alloc] initWithSelectMarr:newDataMarr];
    shopVC.isNegative = self.isNegative;
    [self.navigationController pushViewController:shopVC animated:YES];
    WeakSelf
    shopVC.selectBlock = ^(NSMutableArray<SASalesOrderViewListModel *> * _Nonnull selectMarr) {
        weakSelf.dataMarr = selectMarr;
        [weakSelf.dataMarr addObjectsFromArray:weakSelf.giveDataMarr];
        [weakSelf.tableView reloadData];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            if (weakSelf.tableView.contentSize.height > weakSelf.tableView.frame.size.height){
                CGPoint offset = CGPointMake(0,weakSelf.tableView.contentSize.height -weakSelf.tableView.frame.size.height);
                [weakSelf.tableView setContentOffset:offset animated:NO];
            }
            [weakSelf upData];
            [weakSelf.tableView reloadData];
            [weakSelf setBottomUI];
        });
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.tableView setContentOffset:CGPointMake(0,0) animated:NO];
        });
    };
}

//满减活动规则
-(void)countFullSubtraction {
    
    //计算参与活动的商品数量
    for (SASalesOrderViewListModel *selectModel in self.dataMarr) {
        selectModel.totalCount = 0;
        selectModel.activityTotalCount = 0;
        selectModel.originalTotalSalePrice = 0;
        if (selectModel.isOpenActivity != YES) {
            continue;
        }
        for (SASalesOrderToPendSkuList *list in selectModel.toPendSkuAttrs) {
            selectModel.totalCount += [list.stock integerValue];
            if (selectModel.isGive != YES) {
                selectModel.activityTotalCount += [list.stock integerValue];
            }
        }
        selectModel.originalTotalSalePrice = selectModel.activityTotalCount * [selectModel.retailPrice doubleValue]/100;
        selectModel.originalTotalDiscountPrice= selectModel.activityTotalCount * [selectModel.retailPrice doubleValue]/100 * [selectModel.discountRate doubleValue] / 10000;
        
    }
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    for (SAMarketingListModel *marketingModel in self.marketingMarr) {
        NSMutableArray<SASalesOrderViewListModel *> *activityMarr = [NSMutableArray array];
        mdic[marketingModel.id] = activityMarr;
        for (SASalesOrderViewListModel *selectModel in self.dataMarr) {
            if (selectModel.isGive == YES) {
                selectModel.activityId = @"";
                continue;
            }
            if ([marketingModel.targetProductType isEqualToString:@"0"]) {
                selectModel.activityId = marketingModel.id;
                selectModel.activityPriceType = marketingModel.priceMode;
                selectModel.memberDiscountStacking = marketingModel.memberDiscountStacking;
                selectModel.discountType = marketingModel.discountType;
                selectModel.activityTitle = marketingModel.name;
                [activityMarr addObject:selectModel];
            }else {
                for (NSString *productIdL in marketingModel.productIds) {
                    NSString *productId = [NSString stringWithFormat:@"%@",productIdL];
                    if ([selectModel.productId isEqualToString:productId]) {
                        selectModel.activityId = marketingModel.id;
                        selectModel.activityPriceType = marketingModel.priceMode;
                        selectModel.memberDiscountStacking = marketingModel.memberDiscountStacking;
                        selectModel.discountType = marketingModel.discountType;
                        selectModel.activityTitle = marketingModel.name;
                        [activityMarr addObject:selectModel];
                        break;
                    }
                }
            }
        }
        marketingModel.activityMarr = activityMarr;
    }
    
    for (SAMarketingListModel *marketingModel in self.marketingMarr) {
        
        NSString *achieveType = [NSString stringWithFormat:@"%@",marketingModel.achieveType];
        NSString *priceMode = [NSString stringWithFormat:@"%@",marketingModel.priceMode];
        NSString *discountType = [NSString stringWithFormat:@"%@",marketingModel.discountType];
        NSMutableArray<SASalesOrderViewListModel *> *activityMarr = mdic[marketingModel.id];
        marketingModel.maxDiscountNum = 0;
        marketingModel.totalDiscountMoney = 0;
        marketingModel.totalMoney = 0;
        marketingModel.activityTotalCount = 0;
        marketingModel.triggering = NO;//达不到活动条件
        NSString *activityName = @"";
        
        //如果该活动下没有商品，就不需要继续计算了，不要移动位置，每次计算前要清空储存的值
        if (marketingModel.activityMarr.count == 0) {
            continue;
        }
        
        for (SASalesOrderViewListModel *activityModel in activityMarr) {
            if (activityModel.isOpenActivity == YES && activityModel.isGive != YES) {
                marketingModel.totalDiscountMoney += [activityModel.singleSalePrice doubleValue] * activityModel.activityTotalCount;
                marketingModel.totalMoney += [activityModel.retailPrice doubleValue] / 100 * activityModel.activityTotalCount;
                marketingModel.activityTotalCount += activityModel.activityTotalCount;
            }
        }
        
        if ([achieveType isEqualToString:@"0"]) {
            //取出最小的规则
            SAMarketingRulesModel *minRuleModel = [SAMarketingRulesModel new];
            if (marketingModel.rules.count > 0) {
                minRuleModel = marketingModel.rules[0];
            }
            
            double  marketingtotal = marketingModel.totalMoney;
            if ([priceMode isEqualToString:@"1"]) {
                marketingtotal = marketingModel.totalDiscountMoney;
            }
            
            //满减金额
            if ([discountType isEqualToString:@"0"]) {
                for (SAMarketingRulesModel *ruleModel in marketingModel.rules) {
                    if ([minRuleModel.achieveNum doubleValue] > [ruleModel.achieveNum doubleValue]) {
                        minRuleModel = ruleModel;
                    }
                    if (marketingtotal >= [ruleModel.achieveNum doubleValue]/ 100) {
                        if ([ruleModel.discountNum doubleValue] / 100 > marketingModel.maxDiscountNum) {
                            marketingModel.triggering = YES;//达到活动要求
                            activityName = [NSString stringWithFormat:@"【满%0.lf元减%0.lf元】",[ruleModel.achieveNum doubleValue]/ 100,[ruleModel.discountNum doubleValue]/ 100];
                            marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100;
                            if ([marketingModel.cycle isEqualToString:@"1"]) {
                                NSInteger cycleCount = floor(marketingtotal * 100 /[ruleModel.achieveNum doubleValue]);
                                marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100 * cycleCount ;
                            }
                        }
                    }
                }
                if (activityName.length == 0) {
                    activityName = [NSString stringWithFormat:@"【满%0.lf元减%0.lf元】",[minRuleModel.achieveNum doubleValue]/ 100,[minRuleModel.discountNum doubleValue]/ 100];
                }
            }else { //满减折扣
                for (SAMarketingRulesModel *ruleModel in marketingModel.rules) {
                    if ([minRuleModel.achieveNum doubleValue] > [ruleModel.achieveNum doubleValue]) {
                        minRuleModel = ruleModel;
                    }
                    if (marketingtotal >= [ruleModel.achieveNum doubleValue]/ 100) {
                        if ([ruleModel.discountNum doubleValue] / 100 < marketingModel.maxDiscountNum || marketingModel.maxDiscountNum == 0) {
                            marketingModel.triggering = YES;//达到活动要求
                            activityName = [NSString stringWithFormat:@"【满%0.lf元%0.1lf折】",[ruleModel.achieveNum doubleValue]/ 100,[ruleModel.discountNum doubleValue]/ 1000];
                            marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100;
                            if ([marketingModel.cycle isEqualToString:@"1"]) {
                                NSInteger cycleCount = floor(marketingtotal * 100 /[ruleModel.achieveNum doubleValue]);
                                marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100 * cycleCount ;
                            }
                        }
                    }
                }
                if (activityName.length == 0) {
                    activityName = [NSString stringWithFormat:@"【满%0.lf元%0.1lf折】",[minRuleModel.achieveNum doubleValue]/ 100,[minRuleModel.discountNum doubleValue]/ 1000];
                }
            }
        }else {
            
            //取出最小的规则
            SAMarketingRulesModel *minRuleModel = [SAMarketingRulesModel new];
            if (marketingModel.rules.count > 0) {
                minRuleModel = marketingModel.rules[0];
            }
            
            NSInteger activityTotalCount = marketingModel.activityTotalCount;
            
            //满减金额
            if ([discountType isEqualToString:@"0"]) {
                for (SAMarketingRulesModel *ruleModel in marketingModel.rules) {
                    if ([minRuleModel.achieveNum doubleValue] > [ruleModel.achieveNum doubleValue]) {
                        minRuleModel = ruleModel;
                    }
                    if (activityTotalCount >= [ruleModel.achieveNum doubleValue]) {
                        if ([ruleModel.discountNum doubleValue] / 100 > marketingModel.maxDiscountNum) {
                            marketingModel.triggering = YES;//达到活动要求
                            activityName = [NSString stringWithFormat:@"【满%0.lf件减%0.lf元】",[ruleModel.achieveNum doubleValue],[ruleModel.discountNum doubleValue]/ 100];
                            marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100;
                            if ([marketingModel.cycle isEqualToString:@"1"]) {
                                NSInteger cycleCount = floor(activityTotalCount / [ruleModel.achieveNum doubleValue]);
                                marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100 * cycleCount ;
                            }
                        }
                    }
                }
                if (activityName.length == 0) {
                    activityName = [NSString stringWithFormat:@"【满%0.lf件减%0.lf元】",[minRuleModel.achieveNum doubleValue],[minRuleModel.discountNum doubleValue]/ 100];
                }
            }else { //满减折扣
                for (SAMarketingRulesModel *ruleModel in marketingModel.rules) {
                    if ([minRuleModel.achieveNum doubleValue] > [ruleModel.achieveNum doubleValue]) {
                        minRuleModel = ruleModel;
                    }
                    if (activityTotalCount >= [ruleModel.achieveNum doubleValue]) {
                        if ([ruleModel.discountNum doubleValue] / 100 < marketingModel.maxDiscountNum || marketingModel.maxDiscountNum == 0) {
                            marketingModel.triggering = YES;//达到活动要求
                            activityName = [NSString stringWithFormat:@"【满%0.lf件%0.1lf折】",[ruleModel.achieveNum doubleValue],[ruleModel.discountNum doubleValue]/ 1000];
                            marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100;
                            if ([marketingModel.cycle isEqualToString:@"1"]) {
                                NSInteger cycleCount = floor(activityTotalCount / [ruleModel.achieveNum doubleValue]);
                                marketingModel.maxDiscountNum = [ruleModel.discountNum doubleValue] / 100 * cycleCount ;
                            }
                        }
                    }
                }
                if (activityName.length == 0) {
                    activityName = [NSString stringWithFormat:@"【满%0.lf件%0.1lf折】",[minRuleModel.achieveNum doubleValue],[minRuleModel.discountNum doubleValue]/ 1000];
                }
            }
            
        }
        
        for (SASalesOrderViewListModel *activityModel in activityMarr) {
            activityModel.activityName = activityName;
        }
    }
}

//销售单据
-(void)clickedListBtn {
    
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *isOrder = [NSString stringWithFormat:@"%@",menuList[4][@"isDelete"]];
    NSString *orderOrderList = [NSString stringWithFormat:@"%@",menuList[4][@"perms"][@"orderOrderList"]];
    if ([isOrder isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有订单权限,请联系店长添加" duration:2];
        return;
    }else if ([orderOrderList isEqualToString:@"1"]) {
        [Prompt popPromptViewWithMsg:@"您没有销售单据权限,请联系店长添加" duration:2];
        return;
    }
    
    SASaleDocumentsVC *pushVC = [SASaleDocumentsVC new];
    [self.navigationController pushViewController:pushVC animated:YES];
}

//防止多次结单
- (void)unisversalButtonAcrion:(UIButton *)sender
{
    [[self class] cancelPreviousPerformRequestsWithTarget:self selector:@selector(clickedSettlementBtn) object:sender];
    [self performSelector:@selector(clickedSettlementBtn) withObject:sender afterDelay:0.3f];
}

-(void)clickedSettlementBtn {
    
    WeakSelf
    BOOL isScan = self.isScan;
    if ([self.totalCountLab.text doubleValue] == 0) {
        isScan = NO;
    }
    if (self.isCanPay == NO) {
        isScan = NO;
    }
    SACollectionPayView *payView = [[SACollectionPayView alloc] initWithTotalPrice:self.totalCountLab.text AndIsVip:self.isVip IsScan:isScan PayType:self.defaultPayType];
    [payView showView:self];
    
    payView.settlementBlock = ^(NSString *payType) {
        weakSelf.payType = payType;
        [weakSelf Settlement];
    };
    
    payView.combinationBlock = ^{
        double discountPrice = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] doubleValue];
        double totalPrice = [self.discountPriceTf.text doubleValue] - discountPrice - [self.cardStockTf.text doubleValue];
        if (totalPrice < 0) {
            [Prompt popPromptViewWithMsg:@"卡券金额大于折后金额，请重新填写" duration:2];
            return;
        }
        SAPayCombinationVC *pushVC = [[SAPayCombinationVC alloc] initWithMdic:[weakSelf settlementData]];
        [weakSelf.navigationController pushViewController:pushVC animated:YES];
        pushVC.settlementBlock = ^(NSMutableDictionary * _Nonnull mdic, NSMutableArray * _Nonnull payMarr) {
            weakSelf.isScanPay = NO;
            double price = 0.0;
            for (NSDictionary *dic in payMarr) {
                if ([dic[@"payType"] isEqualToString:@"7"]) {
                    weakSelf.isScanPay = YES;
                    price = [dic[@"payPrice"] doubleValue]/100;
                }
            }
            if (weakSelf.isScanPay == YES) {
                if (price > 10000000) {
                    [Prompt popPromptViewWithMsg:@"金额超出支付限额" duration:2];
                    return;
                }
            }
            weakSelf.salesSaveAPI.coverParameters = mdic;
            [weakSelf.salesSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
        };
    };
}

//结算上传的数据
-(NSMutableDictionary *)settlementData {
    
    NSString *actualPrice = [NSString stringWithFormat:@"%0.lf",[self.totalCountLab.text doubleValue] * 100];
    double discountPrice = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] doubleValue];
    
    NSMutableDictionary *mdic = [NSMutableDictionary dictionary];
    NSMutableArray *payAddFormArray = [[NSMutableArray alloc] init];
    NSMutableArray *detailFormArray = [[NSMutableArray alloc] init];
    
    NSMutableDictionary *basicForm = [NSMutableDictionary dictionary];
    basicForm[@"actualPrice"] = actualPrice;
    basicForm[@"pointCurrent"] = @"0";
    basicForm[@"resideAmount"] = @"0";
    basicForm[@"residePoint"] = @"0";
    basicForm[@"shouldPrice"] = actualPrice;
    [mdic setValue:basicForm forKey:@"basicForm"];
    
    mdic[@"date"] = self.dateBtn.titleLabel.text;
    mdic[@"discountRate"] = [NSString stringWithFormat:@"%0.f",[self.allDiscountTf.text floatValue] * 100];
    if (self.allDiscountTf.text.length == 0) {
        mdic[@"discountRate"] = @"10000";
    }
    mdic[@"empId"] = self.userModel.empId;
    mdic[@"actualPrice"] = actualPrice;
    mdic[@"empType"] = self.userModel.empType;
    mdic[@"remark"] = self.remarkTf.text;
    mdic[@"totalOrderPrice"] = [NSString stringWithFormat:@"%0.f",self.totalPrice];
    mdic[@"deviceId"] = [NSString stringWithFormat:@"%@-%@", kDeviceId, self.userModel.empId];
    mdic[@"cardVoucherPrice"] = [NSString stringWithFormat:@"%0.lf",[self.cardStockTf.text doubleValue] * 100];
    
    NSMutableDictionary *payAddFormDic = [[NSMutableDictionary alloc] init];
    payAddFormDic[@"payType"] = self.payType;
    payAddFormDic[@"payPrice"] = actualPrice;
    [payAddFormArray addObject:payAddFormDic];
    mdic[@"payForms"] = payAddFormArray;
    
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        for (SASalesOrderToPendSkuList *skuList in model.toPendSkuAttrs) {
            if ([skuList.stock integerValue] == 0) {
                continue;
            }
            NSMutableDictionary *detailFormDic = [[NSMutableDictionary alloc] init];
            detailFormDic[@"basicsPrice"] = model.retailPrice;
            detailFormDic[@"count"] = skuList.stock;
            detailFormDic[@"priceType"] = @"1";
            if ([model.priceType isEqualToString:@"-1"]) {
                detailFormDic[@"discountChange"] = @"0";
            }else {
                detailFormDic[@"discountChange"] = @"1";
                detailFormDic[@"priceType"] = model.priceType;
            }
            detailFormDic[@"discountPrice"] = @"0";
            
            if (model.isGive == YES) {
                detailFormDic[@"discountRate"] = @"0";
                detailFormDic[@"price"] = @"0";
            }else if ([model.activityPriceType isEqualToString:@"0"] && model.isOpenActivity == YES) {
                detailFormDic[@"discountRate"] = @"10000";
                detailFormDic[@"price"] = model.retailPrice;
            }else {
                detailFormDic[@"discountRate"] = [NSString stringWithFormat:@"%0.f",model.percentage * 10000];
                detailFormDic[@"price"] = [NSString stringWithFormat:@"%0.lf",[model.singleSalePrice doubleValue] * 100];
            }
            
            detailFormDic[@"productCode"] = model.productCode;
            detailFormDic[@"productId"] = model.productId;
            detailFormDic[@"productName"] = model.productName;
            detailFormDic[@"skuDiscountPrice"] = @"0";
            detailFormDic[@"skuId"] = skuList.skuId;
            detailFormDic[@"totalPrice"] = @"0";
            if (model.isGive == YES) {
                detailFormDic[@"giveFlag"] = @"1";
            }else {
                detailFormDic[@"giveFlag"] = @"0";
            }
            if (model.activityId.length > 0 && model.isOpenActivity == YES) {
                detailFormDic[@"activityId"] = model.activityId;
            }
            
            [detailFormArray addObject:detailFormDic];
        }
    }
    mdic[@"detailForms"] = detailFormArray;
    
    mdic[@"priceOrderRemnantType"] = self.mvoeZero;//0不抹 1抹角 2抹分 3抹角四舍五入 4抹分四舍五入
    mdic[@"priceOrderType"] = self.type;
    mdic[@"shouldPrice"] = actualPrice;
    mdic[@"zeroAmount"] = self.zeroAmount;
    
    mdic[@"balancePrice"] = @"0";
    
    if (self.isVip == YES) {
        basicForm[@"customerName"] = [NSString stringWithFormat:@"%@(%@)",self.vipModel.memberName,self.vipModel.levelName];
        basicForm[@"memberMobile"] = self.vipModel.mobile;
        basicForm[@"pointCurrent"] = [NSString stringWithFormat:@"%0.f",floor(self.sendIntegral * [actualPrice floatValue] / 100)];
        basicForm[@"resideAmount"] = self.vipModel.totalAmount;
        basicForm[@"residePoint"] = self.vipModel.totalPoints;
        
        NSMutableDictionary *vipMdic = [NSMutableDictionary dictionary];
        vipMdic[@"addupConsumeAmount"] = self.vipModel.addupConsumeAmount;
        vipMdic[@"levelName"] = self.vipModel.levelName;
        vipMdic[@"memberDiscount"] = self.vipModel.memberDiscount;
        vipMdic[@"memberId"] = self.vipModel.memberId;
        vipMdic[@"memberLevel"] = self.vipModel.memberLevel;
        vipMdic[@"memberName"] = self.vipModel.memberName;
        vipMdic[@"mobile"] = self.vipModel.mobile;;
        vipMdic[@"totalAmount"] = self.vipModel.totalAmount;
        vipMdic[@"totalPoints"] = self.vipModel.totalPoints;
        mdic[@"memberDataBean"] = vipMdic;
        if (self.discountTf.text.length == 0 ){
            mdic[@"point"] = @"0";
        }else {
            mdic[@"point"] = [NSString stringWithFormat:@"%0.f",[self.discountTf.text floatValue]];
        }
        mdic[@"pointUnit"] = self.limit;
        mdic[@"deductPrice"] = [NSString stringWithFormat:@"%0.f",discountPrice * 100];
        mdic[@"memberId"] = self.vipModel.memberId;
        mdic[@"memberName"] = self.vipModel.memberName;
        mdic[@"deductPoints"] = [NSString stringWithFormat:@"%0.f",[self.discountTf.text floatValue]];
    }
    
    self.isScanPay = [self.payType isEqualToString:@"7"];
    BOOL isScan = self.isScan;
    if (self.totalPrice == 0) {
        isScan = NO;
    }
    if (isScan == YES) {
        mdic[@"scan"] = @"1";
    }
    
    NSData *nData = [NSJSONSerialization dataWithJSONObject:mdic options:0 error:nil];
    mdic[@"randomStr"] = [NSString stringWithFormat:@"%@%@",self.randomStr,[NSString getMD5WithData:nData]];
    return mdic;
}

//结算
-(void)Settlement {
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        NSInteger total = 0;
        for (SASalesOrderToPendSkuList *skuList in model.toPendSkuAttrs) {
            total += [skuList.stock integerValue] ;
        }
        if (total == 0) {
            [Prompt popPromptViewWithMsg:@"数量不符合要求,请重新核对" duration:2];
            return;
        }
    }
    double discountPrice = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] doubleValue];
    double totalPrice = [self.discountPriceTf.text doubleValue] - discountPrice - [self.cardStockTf.text doubleValue];
    if (totalPrice < 0) {
        [Prompt popPromptViewWithMsg:@"卡券金额大于折后金额，请重新填写" duration:2];
        return;
    }
    self.salesSaveAPI.coverParameters = [self settlementData];
    [self.salesSaveAPI sendRequestToServerWithActivityViewAndMask:POST];
}

-(void)clickedUserBtn {
    SASearchStoreUserView *searchStoreUserView = [SASearchStoreUserView shareCornView];
    UIViewController *vc = nil;
    [searchStoreUserView showView:vc];
    WeakSelf
    searchStoreUserView.selectBlock = ^(SAStoreUserModel * _Nonnull userModel) {
        weakSelf.userModel = userModel;
        if (userModel.mobile.length > 0) {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@(%@)",userModel.empName,userModel.mobile] forState:UIControlStateNormal];
        }else {
            [weakSelf.empBtn setTitle:[NSString stringWithFormat:@"%@",userModel.empName] forState:UIControlStateNormal];
        }
        CGFloat imageWidth = weakSelf.empBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.empBtn.titleLabel.bounds.size.width;
        weakSelf.empBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.empBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        [weakSelf.empBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    };
}

-(void)clickedDateBtn {
    WeakSelf
    HDDatePickerView *pickerView = [[HDDatePickerView alloc] initWithSlectedDate:self.dateBtn.titleLabel.text];
    [pickerView show];
    pickerView.selectDateBlock = ^(NSString *selectedDate) {
        [weakSelf.dateBtn setTitle:selectedDate forState:UIControlStateNormal];
    };
}

-(void)clickedVipBtn {
    SASearchVipUserView *searchVipUserView = [SASearchVipUserView shareCornView];
    UIViewController *vc = self;
    searchVipUserView.isAdd = YES;
    [searchVipUserView showView:vc];
    WeakSelf
    searchVipUserView.selectBlock = ^(SAVipModel * _Nonnull vipModel) {
        vipModel.isSuperposition = weakSelf.isSuperposition;
        weakSelf.vipModel = vipModel;
        [weakSelf.vipBtn setTitle:[NSString stringWithFormat:@"%@(%@)",vipModel.memberName,vipModel.mobile] forState:UIControlStateNormal];
        [weakSelf.vipBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        [weakSelf.vipBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
        CGFloat imageWidth = weakSelf.vipBtn.imageView.bounds.size.width;
        CGFloat labelWidth = weakSelf.vipBtn.titleLabel.bounds.size.width;
        weakSelf.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
        weakSelf.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
        weakSelf.isVip = YES;
        weakSelf.remarkView.frame = CGRectMake(0, kScaleNum(StatusHeight + 151), kScreenWidth, kScaleNum(38));
        weakSelf.whiteView2.frame = CGRectMake(0, weakSelf.whiteView.maxY + kScaleNum(7), kScreenWidth, kScaleNum(37));
        weakSelf.tableViewTop = weakSelf.whiteView2.maxY;
        weakSelf.vipIntegralLab.text = [NSString stringWithFormat:@"¥%0.2lf/%@积分",[vipModel.totalAmount doubleValue] / 100,vipModel.totalPoints];
        weakSelf.cancelBtn.hidden = NO;
        weakSelf.discountTf.text = @"";
        weakSelf.integralLab.text = @"可抵:0.00";
        if ([vipModel.totalPoints doubleValue] < 0) {
            weakSelf.vipDiscount = 0;
            weakSelf.discountTf.placeholder = [NSString stringWithFormat:@"%0.f积分可抵扣0.00",weakSelf.vipDiscount];
        }else if ([vipModel.totalPoints doubleValue] > [weakSelf.discount doubleValue] * [weakSelf.limit doubleValue]) {
            weakSelf.vipDiscount = [weakSelf.discount doubleValue] * [weakSelf.limit doubleValue];
            weakSelf.discountTf.placeholder = [NSString stringWithFormat:@"%0.f积分可抵扣%@",weakSelf.vipDiscount,weakSelf.limit];
        }else {
            weakSelf.vipDiscount = [vipModel.totalPoints doubleValue];
            weakSelf.discountTf.placeholder = [NSString stringWithFormat:@"%0.f积分可抵扣%0.2lf",weakSelf.vipDiscount, floor(weakSelf.vipDiscount * 100 /[weakSelf.discount doubleValue])/100];
        }
        
        //处理开启活动折上折，改变了会员
        for (SASalesOrderViewListModel *model in weakSelf.dataMarr) {
            if (![model.priceType isEqualToString:@"-1"]) {
                if (model.isOpenActivity == YES && [model.memberDiscountStacking isEqualToString:@"1"]) {
                    model.percentage = model.activityPercentage * [weakSelf.vipModel.memberDiscount doubleValue]/100;;
                    model.salePrice = model.activitySalePrice * [weakSelf.vipModel.memberDiscount doubleValue]/100;
                }
                
            }
        }
        [weakSelf.tableView reloadData];
        [weakSelf setBottomUI];
    };
}

-(void)clickedCancelBtn {
    self.cancelBtn.hidden = YES;
    self.isVip = NO;
    self.vipModel = nil;
    
    self.remarkView.frame = CGRectMake(0, kScaleNum(StatusHeight + 113), kScreenWidth, kScaleNum(38));
    self.whiteView2.frame = CGRectMake(0, self.whiteView.maxY - kScaleNum(38) + kScaleNum(7), kScreenWidth, kScaleNum(37));
    self.tableViewTop = self.whiteView2.maxY;
    
    //处理开启活动折上折，取消了会员
    for (SASalesOrderViewListModel *model in self.dataMarr) {
        if (![model.priceType isEqualToString:@"-1"]) {
            if (model.isOpenActivity == YES && [model.memberDiscountStacking isEqualToString:@"1"]) {
                model.percentage = model.activityPercentage;
                model.salePrice = model.activitySalePrice;
            }
            
        }
    }
    [self.tableView reloadData];
    [self setBottomUI];
    [self.vipBtn setTitle:@"请选择会员" forState:UIControlStateNormal];
    [self.vipBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
    CGFloat imageWidth = self.vipBtn.imageView.bounds.size.width;
    CGFloat labelWidth = self.vipBtn.titleLabel.bounds.size.width;
    self.vipBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
    self.vipBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
}

-(void)upData {
    
    //当有活动的时候，需要刷新，确保 totalSalePrice 的值正确
    //    [self.tableView reloadData];
    [self countFullSubtraction];
    
    if (self.dataMarr.count > 0) {
        
        //处理活动满减
        double marketingTotal = 0.0;//满减
        double discountTotal = 0.0;//折扣减少的金额
        NSInteger num = 0;
        double total = 0;
        double retailTotal = 0;
        BOOL isTriggering = NO;//没有商品参加活动
        
        for (SASalesOrderViewListModel *model in self.dataMarr) {
            for (SASalesOrderToPendSkuList *list in model.toPendSkuAttrs) {
                num += [list.stock integerValue];
                retailTotal += [model.retailPrice doubleValue] * [list.stock integerValue];
            }
            //参加活动折扣需要重新计算
            if (model.isOpenActivity == YES && [model.discountType isEqualToString:@"1"]) {
                continue;
            }
            
            NSString *totalSalePrice = [NSString stringWithFormat:@"%0.2lf",round(model.totalSalePrice * 100.f)/100];
            total += [totalSalePrice doubleValue];
        }
        
        for (SAMarketingListModel *marketingModel in self.marketingMarr) {
            if (marketingModel.triggering == YES) {
                isTriggering = YES;
            }
            
            if ([marketingModel.discountType isEqualToString:@"1"]) {
                double marketingDiscountTotal = 0.0;
                for (SASalesOrderViewListModel *model in marketingModel.activityMarr) {
                    if (model.isOpenActivity == YES) {
                        marketingDiscountTotal += model.totalSalePrice;
                    }
                }
                if (marketingModel.triggering == YES) {
                    total += marketingDiscountTotal * marketingModel.maxDiscountNum / 100;
                    discountTotal += (marketingDiscountTotal - marketingDiscountTotal * marketingModel.maxDiscountNum / 100);
                }else {
                    total += marketingDiscountTotal;
                }
                
            }else {
                marketingTotal += marketingModel.maxDiscountNum;
            }
        }
        
        total = total - marketingTotal;
        self.totalPrice = total * 100;
        
        self.shopLab.text = [NSString stringWithFormat:@"选择商品(%zd)",num];
        self.shopLab.textColor = kBlackColor;
        [self.shopLab setAttributedStringWithSubString:[NSString stringWithFormat:@"%zd",num] color:kPinkColor];
        self.shopPirceLab.text = [NSString stringWithFormat:@"￥%0.2lf",total];
        
        if (total == retailTotal/100) {
            self.shopPirceLab.hidden = false;
            self.shopPirce1Lab.hidden = true;
            self.shopPirce2Lab.hidden = true;
        }else {
            self.shopPirceLab.hidden = true;
            self.shopPirce1Lab.hidden = false;
            self.shopPirce2Lab.hidden = false;
            self.shopPirce1Lab.text = [NSString stringWithFormat:@"￥%0.2lf",total];
            
            NSString *textContent = [NSString stringWithFormat:@"原价%0.2lf",round(retailTotal) / 100];
            NSMutableDictionary *textDict = [NSMutableDictionary dictionary];
            textDict[NSStrikethroughColorAttributeName] = kPinkColor;
            textDict[NSForegroundColorAttributeName] = kLightgGrayColor;
            textDict[NSFontAttributeName] = kFont(14);
            textDict[NSStrikethroughStyleAttributeName] = [NSNumber numberWithInteger:NSUnderlineStyleSingle];
            textDict[NSBaselineOffsetAttributeName] = @(NSUnderlineStyleSingle);
            self.shopPirce2Lab.attributedText = [[NSAttributedString alloc] initWithString:textContent attributes:textDict];
        }
        
        if (isTriggering == YES) {
            self.marketingLab.font = kFont(13);
            self.marketingLab.text = [NSString stringWithFormat:@"%zd件，%0.2lf元，满减优惠%0.2lf元\n满减折后价%0.2lf元" ,num, retailTotal/100, marketingTotal + discountTotal, total];
        }else {
            self.marketingLab.font = kFont(15);
            self.marketingLab.text = [NSString stringWithFormat:@"%zd件，%0.2lf元，商品折后价%0.2lf元" ,num, retailTotal/100, total];
        }
        
    }else {
        self.shopLab.text = @"选择商品";
        self.shopLab.textColor = kBlackColor;
        self.allDiscountTf.text = @"100.00";
        self.shopPirceLab.text = @"";
        self.shopPirceLab.hidden = false;
        self.shopPirce1Lab.hidden = true;
        self.shopPirce2Lab.hidden = true;
        [self.view endEditing:YES];
    }
    [self countPrice];
}

-(void)countPrice {
    NSString *priceStr = [self.shopPirceLab.text stringByReplacingOccurrencesOfString:@"￥" withString:@""];
    double price = [[NSString stringWithFormat:@"%0.f",[priceStr doubleValue] * 100] doubleValue];
    NSInteger allDiscount = 10000;
    if (self.allDiscountTf.text.length > 0) {
        NSString *allDiscountStr = [NSString stringWithFormat:@"%0.f",[self.allDiscountTf.text floatValue] * 100];
        allDiscount = [allDiscountStr integerValue];
    }
    double discount = price * allDiscount / 100;
    self.discountPriceTf.text = [NSString stringWithFormat:@"%0.2lf",discount /10000.f];
    
    CGFloat discountPriceF = [[self.integralLab.text stringByReplacingOccurrencesOfString:@"可抵:" withString:@""] floatValue];
    double discountPrice = [[NSString stringWithFormat:@"%0.f",discountPriceF * 100] doubleValue];
    //    NSString *discountPriceTfstr = self.discountPriceTf.text;
    double totalPrice = [self.discountPriceTf.text doubleValue] * 100 - discountPrice - [self.cardStockTf.text doubleValue] * 100;
    if (totalPrice < 0) {
        totalPrice = 0;
    }
    self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",totalPrice / 100];
    double newTotalPrice = [[NSString stringWithFormat:@"%0.f",totalPrice] doubleValue];
    if ([self.mvoeZero isEqualToString:@"1"]) {
        self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",floor(newTotalPrice/100)];
    }else if ([self.mvoeZero isEqualToString:@"2"]) {
        self.totalCountLab.text = [NSString stringWithFormat:@"%0.2lf",floor(newTotalPrice / 10) / 10.f];
    }else if ([self.mvoeZero isEqualToString:@"3"]) {
        NSString *countStr = [NSString stringWithFormat:@"%0.lf",round(newTotalPrice/100.f)];
        self.totalCountLab.text = [NSString stringWithFormat:@"%@.00",countStr];
    }else if ([self.mvoeZero isEqualToString:@"4"]) {
        NSString *countStr = [NSString stringWithFormat:@"%0.1lf",round(newTotalPrice/10.f)/10];
        self.totalCountLab.text = [NSString stringWithFormat:@"%@0",countStr];
    }
    
    double totalCountD = [self.totalCountLab.text doubleValue] * 100;
    double zeroAmountD = newTotalPrice - totalCountD;
    self.zeroAmount = [NSString stringWithFormat:@"%0.lf",zeroAmountD];
}

-(void)setBottomUI {
    if (self.dataMarr.count > 0) {
        
        self.footView.hidden = NO;
        if (self.isVip == YES && self.pointSwitch == YES) {
            self.integralView.hidden = YES;
            self.scanBtn.frame = CGRectMake(kScaleNum(76), kScreenHeight - kScaleNum(298) - SafeFooterHeight, kScaleNum(53), kScaleNum(40));
            self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), kScreenHeight - kScaleNum(298) - SafeFooterHeight, kScaleNum(53), kScaleNum(40));
        }else {
            self.integralView.hidden = NO;
            self.scanBtn.frame = CGRectMake(kScaleNum(76), kScreenHeight - kScaleNum(263) - SafeFooterHeight, kScaleNum(53), kScaleNum(40));
            self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), kScreenHeight - kScaleNum(263) - SafeFooterHeight, kScaleNum(53), kScaleNum(40));
        }
    }else {
        self.footView.hidden = YES;
        self.scanBtn.frame = CGRectMake(kScaleNum(76),  self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(40));
        self.addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), self.tableViewTop + kScaleNum(10), kScaleNum(53), kScaleNum(40));
        self.discountTf.text = @"";
        self.cardStockTf.text = @"";
    }
    self.tableView.frame = CGRectMake(0, self.tableViewTop, kScreenWidth, self.scanBtn.y - self.tableViewTop - kScaleNum(8));
    [self.tableView reloadData];
}

-(void)clearData {
    [self.dataMarr removeAllObjects];
    [self.tableView reloadData];
    [self upData];
    [self setBottomUI];
    [self clickedCancelBtn];
    self.allDiscountTf.text = @"100.00";
    self.discountTf.text = @"";
    self.integralLab.text = @"可抵:0.00";
    self.cardStockTf.text = @"";
    self.remarkTf.text = @"";
    self.randomStr = [NSString random:10];
}

//扫码
-(void)scanQrcode {
    WeakSelf
    __block NSString *salesOrderId = self.salesOrderId;
    __block NSString *salesOrderNo = self.salesOrderNo;
    [self.navigationController pushViewController:[[ScanHelper shareInstance] ScanVCWithStyle:weixinStyle qrResultCallBack:^(id result) {
        weakSelf.salesSalesPayAPI.authCode = result;
        weakSelf.salesSalesPayAPI.salesOrderId = salesOrderId;
        weakSelf.salesSalesPayAPI.salesOrderNo = salesOrderNo;
        [weakSelf.salesSalesPayAPI sendRequestToServerWithActivityViewAndMask:POST];
        [self.navigationController popViewControllerAnimated:NO];
    }] animated:YES];
}

- (void)timerFired {
    if (self.count != 1) {
        self.count -= 1;
        [self.receiveQueryStatusAPI sendRequestToServerWithType:POST];
    } else {
        self.isPolling = NO;
        // 停掉定时器
        [self.timer invalidate];
        self.timer = nil;
        [HDHubView dismissLoading];
    }
}

-(void)tipAlertView:(NSString *)msg {
    GFAlertView *alertView = [GFAlertView alertViewWithMsg:@"提示" detailMsg:msg leftBtnBlock:^(UIButton *leftBtn) {
        [leftBtn setTitle:@"取消" forState:UIControlStateNormal];
        [leftBtn addTarget:self action:@selector(cancelPay) forControlEvents:UIControlEventTouchUpInside];
    } rightBtnBlock:^(UIButton *rightBtn) {
        [rightBtn setTitle:@"重试" forState:UIControlStateNormal];
        [rightBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        [rightBtn addTarget:self action:@selector(continuePay) forControlEvents:UIControlEventTouchUpInside];
    }];
    
    [alertView showWithAnimation];
}

-(void)continuePay {
    [self scanQrcode];
}

-(void)cancelPay {
    [self clearData];
}

-(void)showImage:(NSArray *)imageList {
    self.imageList = imageList;
    if (self.imageList.count > 0) {
        NSMutableArray *imageMarr = [NSMutableArray array];
        for (NSString *url in self.imageList) {
            NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"?x-oss-process=style/thumbnail" withString:@""];
            NSString *imageUrl = [NSString stringWithFormat:@"%@?x-oss-process=image/resize,l_720",newUrl];
            [imageMarr addObject:imageUrl];
        }
        self.imageList = imageMarr;
        YBImageBrowser *browser = [YBImageBrowser new];
        browser.dataSourceArray = self.imageList;
        browser.dataSource = self;
        browser.currentPage = 0;
        [browser show];
    }else {
        [Prompt popPromptViewWithMsg:@"该商品没有图片" duration:2];
    }
}

//YBImageBrowserDataSource 代理实现赋值数据
- (NSInteger)yb_numberOfCellsInImageBrowser:(YBImageBrowser *)imageBrowser {
    return self.imageList.count;
}

- (id<YBIBDataProtocol>)yb_imageBrowser:(YBImageBrowser *)imageBrowser dataForCellAtIndex:(NSInteger)index {
    NSString *urlStr = [self.imageList objectAtIndex:index];
    YBIBImageData *data = [YBIBImageData new];
    data.imageURL = [NSURL URLWithString:urlStr];
    return data;
}

#pragma mark - initUI
-(void)initUI {
    [self setNavigationItemBackBBIAndTitle:@"商品销售"];
    [self setBgImage:nil];
    self.randomStr = [NSString random:10];
    
    SAUserInfo *model = [SAValueManger shareInStance].userInfo;
    self.type = @"1";
    self.payType = @"1";
    
    self.isScan = [[SAValueManger shareInStance].userInfo.auditStatus isEqualToString:@"1"];
    BOOL isPayChannel = ![[SAValueManger shareInStance].userInfo.payChannel isEqualToString:@"2"];
    if (self.isScan == YES) {
        self.isScan = isPayChannel;
    }
    
    UIButton *listBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    listBtn.frame = CGRectMake(0, 0, kScaleNum(60), kScaleNum(44));
    [listBtn setImage:[UIImage imageNamed:@"shopSale_list"] forState:UIControlStateNormal];
    [listBtn addTarget:self action:@selector(clickedListBtn) forControlEvents:UIControlEventTouchUpInside];
    [self addRightViews:@[listBtn]];
    
    self.view.backgroundColor = kBgColor;
    
    UIView *whiteView = [[UIView alloc] initWithFrame:SARectMake(0, StatusHeight, kBaseScreenWidth, 189)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView];
    self.whiteView = whiteView;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *timeFormatStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSArray *nameArr = @[@"  店员", @"  日期", @"  会员", @"  会员余额/积分"];
    NSArray *imageArr = @[@"Sale_user", @"Sale_clock", @"Sale_vip", @"Warehousing_icon_5"];
    
    for (int i = 0; i < nameArr.count; i++) {
        UIButton *titleBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [titleBtn setImage:[UIImage imageNamed:imageArr[i]] forState:UIControlStateNormal];
        [titleBtn setTitle:nameArr[i] forState:UIControlStateNormal];
        titleBtn.frame = SARectMake(20, StatusHeight + i * 38, 120, 37);
        titleBtn.titleLabel.font = kFont(15);
        [titleBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
        titleBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [self.view addSubview:titleBtn];
        
        if (i < 3) {
            UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [rightBtn setImage:[UIImage imageNamed:@"Sale_rightArrow"] forState:UIControlStateNormal];
            rightBtn.frame = SARectMake(0, StatusHeight + i * 38, kBaseScreenWidth - 20, 37);
            rightBtn.titleLabel.font = kFont(15);
            [rightBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
            rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
            [self.view addSubview:rightBtn];
            if (i == 0) {
                [rightBtn setTitle:[NSString stringWithFormat:@"%@(%@)",model.empName,model.mobile] forState:UIControlStateNormal];
                [rightBtn addTarget:self action:@selector(clickedUserBtn) forControlEvents:UIControlEventTouchUpInside];
                self.empBtn = rightBtn;
            }else if (i == 1) {
                [rightBtn setTitle:timeFormatStr forState:UIControlStateNormal];
                self.dateBtn = rightBtn;
                [rightBtn addTarget:self action:@selector(clickedDateBtn) forControlEvents:UIControlEventTouchUpInside];
            }else {
                [rightBtn setTitle:@"请选择会员" forState:UIControlStateNormal];
                [rightBtn setTitleColor:kLightgGrayColor forState:UIControlStateNormal];
                self.vipBtn = rightBtn;
                [rightBtn addTarget:self action:@selector(clickedVipBtn) forControlEvents:UIControlEventTouchUpInside];
            }
            CGFloat imageWidth = rightBtn.imageView.bounds.size.width;
            CGFloat labelWidth = rightBtn.titleLabel.bounds.size.width;
            rightBtn.imageEdgeInsets = UIEdgeInsetsMake(0, labelWidth, 0, -labelWidth);
            rightBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -imageWidth-10, 0, imageWidth + 10);
            
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(20, StatusHeight + i * 38 + 37, kBaseScreenWidth - 40, 1)];
            line.backgroundColor = kLineColor;
            [self.view addSubview:line];
        }
        
        if (i == 3) {
            UILabel *vipIntegralLab = [[UILabel alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
            vipIntegralLab.text = @"";
            vipIntegralLab.font = kFont(15);
            vipIntegralLab.frame = SARectMake(kBaseScreenWidth - 270, StatusHeight + i * 38, 250, 37);
            vipIntegralLab.textAlignment = NSTextAlignmentRight;
            vipIntegralLab.textColor = kGrayColor;
            self.vipIntegralLab = vipIntegralLab;
            [self.view addSubview:vipIntegralLab];
        }
    }
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setImage:[UIImage imageNamed:@"btn_cancle"] forState:UIControlStateNormal];
    cancelBtn.frame = SARectMake(kBaseScreenWidth - 37, StatusHeight + 2 * 38, 30, 37);
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn addTarget:self action:@selector(clickedCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    cancelBtn.hidden = YES;
    self.cancelBtn = cancelBtn;
    [self.view addSubview:cancelBtn];
    
    //处理会员积分
    UIView *topGrayView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight +151), kScreenWidth, kScaleNum(38))];
    topGrayView.backgroundColor = kBgColor;
    [self.view addSubview:topGrayView];
    
    UIView *remarkView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(StatusHeight + 113), kScreenWidth, kScaleNum(38))];
    remarkView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:remarkView];
    self.remarkView = remarkView;
    
    UIView *remarkLine = [[UIView alloc] initWithFrame:SARectMake(20, 0, kBaseScreenWidth - 40, 1)];
    remarkLine.backgroundColor = kLineColor;
    [remarkView addSubview:remarkLine];
    
    UIButton *remarkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [remarkBtn setImage:[UIImage imageNamed:@"Warehousing_icon_5"] forState:UIControlStateNormal];
    [remarkBtn setTitle:@"  备注" forState:UIControlStateNormal];
    remarkBtn.frame = SARectMake(20, 1, 120, 37);
    remarkBtn.titleLabel.font = kFont(15);
    [remarkBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
    remarkBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [remarkView addSubview:remarkBtn];
    
    UITextField *remarkTf = [[UITextField alloc] initWithFrame:SARectMake(0, 7, 249, 30)];
    remarkTf.placeholder = @"请输入备注";
    remarkTf.text = @"";
    remarkTf.font = kFont(15);
    remarkTf.clearButtonMode = UITextFieldViewModeWhileEditing;
    remarkTf.frame = SARectMake(kBaseScreenWidth - 270, 1, 250, 37);
    remarkTf.textAlignment = NSTextAlignmentRight;
    self.remarkTf = remarkTf;
    [remarkView addSubview:remarkTf];
    
    UIView *whiteView2 = [[UIView alloc] initWithFrame:CGRectMake(0, whiteView.maxY - kScaleNum(38) + kScaleNum(7), kScreenWidth, kScaleNum(37))];
    whiteView2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:whiteView2];
    self.whiteView2 = whiteView2;
    
    UILabel *shopLab = [[UILabel alloc] initWithFrame:SARectMake(20, 0, 150, 37)];
    shopLab.text = @"选择商品";
    shopLab.textColor = kBlackColor;
    shopLab.font = kFont(15);
    [whiteView2 addSubview:shopLab];
    self.shopLab = shopLab;
    
    UILabel *shopPirceLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 190, 0, 170, 37)];
    shopPirceLab.textColor = kBlackColor;
    shopPirceLab.text = @"";
    shopPirceLab.font = kFont(14);
    shopPirceLab.textAlignment = NSTextAlignmentRight;
    [whiteView2 addSubview:shopPirceLab];
    self.shopPirceLab = shopPirceLab;
    
    UILabel *shopPirce1Lab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 190, 3, 170, 15)];
    shopPirce1Lab.textColor = kBlackColor;
    shopPirce1Lab.text = @"";
    shopPirce1Lab.font = kFont(15);
    shopPirce1Lab.textAlignment = NSTextAlignmentRight;
    [whiteView2 addSubview:shopPirce1Lab];
    self.shopPirce1Lab = shopPirce1Lab;
    
    UILabel *shopPirce2Lab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 190, 19, 170, 15)];
    shopPirce2Lab.textColor = kLightgGrayColor;
    shopPirce2Lab.text = @"";
    shopPirce2Lab.font = kFont(14);
    shopPirce2Lab.textAlignment = NSTextAlignmentRight;
    [whiteView2 addSubview:shopPirce2Lab];
    self.shopPirce2Lab = shopPirce2Lab;
    
    self.tableViewTop = whiteView2.maxY;
    [self.view addSubview:self.tableView];
    
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kScaleNum(250) - SafeFooterHeight, kScreenWidth, kScaleNum(250) + SafeFooterHeight)];
    footView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:footView];
    footView.hidden = YES;
    self.footView = footView;
    
    NSArray *titleArr = @[@"抵扣积分",@"",@"整单折扣",@"折后金额",@"卡劵",@"本单应收"];
    for (int i = 0; i < titleArr.count; i++) {
        UILabel *lab = [[UILabel alloc] initWithFrame:SARectMake(20, i * 35, 100, 35)];
        lab.text = titleArr[i];
        lab.font = kFont(15);
        lab.textColor = kBlackColor;
        [footView addSubview:lab];
        if (i == 1) {
            self.marketingLab = lab;
            lab.frame = SARectMake(20, i * 35, kBaseScreenWidth - 40, 35);
            lab.numberOfLines = 2;
        }
        
        if (i == 5) {
            lab.textColor = kLightgGrayColor;
        }else {
            UIView *line = [[UIView alloc] initWithFrame:SARectMake(0, 34 + i * 35, kBaseScreenWidth, 1)];
            line.backgroundColor = kLineColor;
            [footView addSubview:line];
        }
    }
    
    UITextField *discountTf = [[UITextField alloc] initWithFrame:SARectMake(100, 0, 175, 35)];
    discountTf.placeholder = @"0积分抵扣0元";
    discountTf.userInteractionEnabled = NO;
    discountTf.font = kFont(15);
    discountTf.textColor = kBlackColor;
    discountTf.delegate = self;
    discountTf.textAlignment = NSTextAlignmentCenter;
    [footView addSubview:discountTf];
    [discountTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.discountTf = discountTf;
    
    UILabel *integralLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 130, 0, 110, 35)];
    integralLab.text = @"可抵:0.00";
    integralLab.font = kFont(15);
    integralLab.textColor = kBlackColor;
    integralLab.textAlignment = NSTextAlignmentRight;
    [footView addSubview:integralLab];
    self.integralLab = integralLab;
    
    UIView *integralView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScaleNum(35))];
    integralView.backgroundColor = kBgColor;
    [footView addSubview:integralView];
    self.integralView = integralView;
    
    UITextField *allDiscountTf = [[UITextField alloc] initWithFrame:SARectMake(kBaseScreenWidth - 210, 70, 170, 35)];
    allDiscountTf.text = @"100.00";
    allDiscountTf.font = kFont(15);
    allDiscountTf.textColor = kBlackColor;
    allDiscountTf.textAlignment = NSTextAlignmentRight;
    [footView addSubview:allDiscountTf];
    allDiscountTf.delegate = self;
    allDiscountTf.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
    [allDiscountTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.allDiscountTf = allDiscountTf;
    
    UILabel *percentageLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 35, 70, 15, 35)];
    percentageLab.text = @"%";
    percentageLab.font = kFont(15);
    percentageLab.textColor = kBlackColor;
    percentageLab.textAlignment = NSTextAlignmentRight;
    [footView addSubview:percentageLab];
    
    UITextField *discountPriceTf = [[UITextField alloc] initWithFrame:SARectMake(kBaseScreenWidth - 210, 105, 190, 35)];
    discountPriceTf.font = kFont(15);
    discountPriceTf.textColor = kBlackColor;
    discountPriceTf.textAlignment = NSTextAlignmentRight;
    [footView addSubview:discountPriceTf];
    discountPriceTf.delegate = self;
    [discountPriceTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.discountPriceTf = discountPriceTf;
    
    UITextField *cardStockTf = [[UITextField alloc] initWithFrame:SARectMake(kBaseScreenWidth - 210, 140, 190, 35)];
    cardStockTf.font = kFont(15);
    cardStockTf.textColor = kBlackColor;
    cardStockTf.textAlignment = NSTextAlignmentRight;
    [footView addSubview:cardStockTf];
    cardStockTf.delegate = self;
    [cardStockTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.cardStockTf = cardStockTf;
    
    UILabel *totalCountLab = [[UILabel alloc] initWithFrame:SARectMake(kBaseScreenWidth - 210, 175, 190, 35)];
    totalCountLab.font = kFont(15);
    totalCountLab.textColor = kBlackColor;
    totalCountLab.textAlignment = NSTextAlignmentRight;
    [footView addSubview:totalCountLab];
    self.totalCountLab = totalCountLab;
    
    UIButton *settlementBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    settlementBtn.frame = CGRectMake(0, kScaleNum(210), kScreenWidth, kScaleNum(40) + SafeFooterHeight);
    [settlementBtn setBackgroundImage:[UIImage imageNamed:@"top_image"] forState:UIControlStateNormal];
    [settlementBtn setTitle:@"结算" forState:UIControlStateNormal];
    settlementBtn.titleLabel.font = kBFont(18);
    [settlementBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [settlementBtn addTarget:self action:@selector(unisversalButtonAcrion:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:settlementBtn];
    
    UIButton *scanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [scanBtn setImage:[UIImage imageNamed:@"Sale_scan"] forState:UIControlStateNormal];
    scanBtn.frame = CGRectMake(kScaleNum(76), whiteView2.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(40));
    scanBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [scanBtn addTarget:self action:@selector(clickedScanBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:scanBtn];
    self.scanBtn = scanBtn;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"Sale_Add"] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(kScreenWidth - kScaleNum(120), whiteView2.maxY + kScaleNum(10), kScaleNum(53), kScaleNum(40));
    addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [addBtn addTarget:self action:@selector(clickedAddBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addBtn];
    self.addBtn = addBtn;
    
    //权限处理
    NSMutableArray *menuList = [SAValueManger shareInStance].userInfo.menuList;
    NSString *salesDiscount = [NSString stringWithFormat:@"%@",menuList[11][@"perms"][@"salesDiscount"]];
    if ([salesDiscount isEqualToString:@"1"]) {
        discountTf.userInteractionEnabled = NO;
        allDiscountTf.userInteractionEnabled = NO;
        discountPriceTf.userInteractionEnabled = NO;
        cardStockTf.userInteractionEnabled = NO;
    }
    
    self.getOrgMerchantSettingsAPI.code = @"points_switch";
    [self.getOrgMerchantSettingsAPI sendRequestToServerWithActivityViewAndMask:GET];
    [self.allInProgressActivityAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    self.systemEmpDetailAPI.empId = model.empId;
    [self.systemEmpDetailAPI sendRequestToServerWithActivityViewAndMask:GET];
    
    self.overallSetting = [SAOverallSetting shareInstance];
    
    self.isCanPay = NO;
    [self.getPayPermissionAPI sendRequestToServerWithActivityViewAndMask:POST];
}

#pragma mark - lazy
-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.tableViewTop, kScreenWidth, kScaleNum(200)) style:UITableViewStyleGrouped];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = kBgColor;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SAShopSaleCell class] forCellReuseIdentifier:@"SAShopSaleCell"];
        [_tableView registerClass:[SAShopSaleFooterView class] forHeaderFooterViewReuseIdentifier:@"SAShopSaleFooterView"];
    }
    return _tableView;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(SASystemSettingsListAPI *)systemSettingsListAPI {
    if (!_systemSettingsListAPI) {
        _systemSettingsListAPI = [SASystemSettingsListAPI apiWithDelegate:self];
    }
    return _systemSettingsListAPI;
}

-(SASalesSaveAPI *)salesSaveAPI {
    if (!_salesSaveAPI) {
        _salesSaveAPI = [SASalesSaveAPI apiWithDelegate:self];
        _salesSaveAPI.isPromptErrorMessage = NO;
    }
    return _salesSaveAPI;
}

-(SASalesInvoiceDetailAPI *)salesInvoiceDetailAPI {
    if (!_salesInvoiceDetailAPI) {
        _salesInvoiceDetailAPI = [SASalesInvoiceDetailAPI apiWithDelegate:self];
    }
    return _salesInvoiceDetailAPI;
}

-(SASystemEmpDetailAPI *)systemEmpDetailAPI {
    if (!_systemEmpDetailAPI) {
        _systemEmpDetailAPI = [SASystemEmpDetailAPI apiWithDelegate:self];
    }
    return _systemEmpDetailAPI;
}

-(SASalesProductListAPI *)salesProductListAPI {
    if (!_salesProductListAPI) {
        _salesProductListAPI = [SASalesProductListAPI apiWithDelegate:self];
    }
    return _salesProductListAPI;
}

-(SACloudPrintPushPrintMsgAPI *)cloudPrintPushPrintMsgAPI {
    if (!_cloudPrintPushPrintMsgAPI) {
        _cloudPrintPushPrintMsgAPI = [SACloudPrintPushPrintMsgAPI apiWithDelegate:self];
    }
    return _cloudPrintPushPrintMsgAPI;
}

-(SASalesSalesPayAPI *)salesSalesPayAPI {
    if (!_salesSalesPayAPI) {
        _salesSalesPayAPI = [SASalesSalesPayAPI apiWithDelegate:self];
        _salesSalesPayAPI.isPromptErrorMessage = NO;
    }
    return _salesSalesPayAPI;
}

-(SAReceiveQueryStatusAPI *)receiveQueryStatusAPI {
    if (!_receiveQueryStatusAPI) {
        _receiveQueryStatusAPI = [SAReceiveQueryStatusAPI apiWithDelegate:self];
        _receiveQueryStatusAPI.isPromptErrorMessage = NO;
    }
    return _receiveQueryStatusAPI;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

-(SAGetPayPermissionAPI *)getPayPermissionAPI {
    if (!_getPayPermissionAPI) {
        _getPayPermissionAPI = [SAGetPayPermissionAPI apiWithDelegate:self];
    }
    return _getPayPermissionAPI;
}

-(SAQueryPrinterStatusAPI *)queryPrinterStatusAPI {
    if (!_queryPrinterStatusAPI) {
        _queryPrinterStatusAPI = [SAQueryPrinterStatusAPI apiWithDelegate:self];
    }
    return _queryPrinterStatusAPI;
}

-(SAPrintTicketAPI *)printTicketAPI {
    if (!_printTicketAPI) {
        _printTicketAPI = [SAPrintTicketAPI apiWithDelegate:self];
    }
    return _printTicketAPI;
}

-(NSMutableArray<SASalesOrderViewListModel *> *)giveDataMarr {
    if (!_giveDataMarr) {
        _giveDataMarr = [NSMutableArray array];
    }
    return _giveDataMarr;
}

-(SAAllInProgressActivityAPI *)allInProgressActivityAPI {
    if (!_allInProgressActivityAPI) {
        _allInProgressActivityAPI = [SAAllInProgressActivityAPI apiWithDelegate:self];
    }
    return _allInProgressActivityAPI;
}

-(NSMutableArray<SAMarketingListModel *> *)marketingMarr {
    if (!_marketingMarr) {
        _marketingMarr = [NSMutableArray array];
    }
    return _marketingMarr;
}

-(SAGetOrgMerchantSettingsAPI *)getOrgMerchantSettingsAPI {
    if (!_getOrgMerchantSettingsAPI) {
        _getOrgMerchantSettingsAPI = [SAGetOrgMerchantSettingsAPI apiWithDelegate:self];
    }
    return _getOrgMerchantSettingsAPI;
}

@end

